const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../../uploads/'))
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}${ext}`)
  }
});

const upload = multer({
  storage: storage,
  fileFilter: function (req, file, cb) {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      // 设置错误信息和req.file状态
      req.fileError = '只支持JPEG、PNG和GIF格式的图片';
      req.file = null;
      cb(null, false); // 告诉Multer跳过此文件
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

// 导出多文件上传中间件，添加错误处理包装
const uploadMiddleware = upload.fields([
   { name: 'image', maxCount: 1 }
])

// 导出multer实例，用于自定义字段配置
module.exports = {
  upload,
  uploadMiddleware
};